import React, { useEffect, useRef } from 'react'
import { Modal, Form } from 'antd'
import type { ModalProps } from 'antd'
import type { FormInstance } from 'antd/es/form'

interface ProModalProps extends Omit<ModalProps, 'onOk' | 'onCancel'> {
  form?: FormInstance
  onFinish?: (values: any) => void
  onOk?: (e: React.MouseEvent<HTMLElement>) => void
  onCancel?: (e: React.MouseEvent<HTMLElement>) => void
  children: React.ReactNode
}

const ProModal: React.FC<ProModalProps> = ({
  form,
  onFinish,
  children,
  onOk,
  onCancel,
  open,
  afterClose,
  ...props
}) => {
  const modalRef = useRef<HTMLDivElement>(null)

  // 清理模态框
  const cleanupModal = () => {
    // 查找当前模态框的根元素
    const modalRoot = modalRef.current?.closest('.ant-modal-root')
    if (modalRoot && modalRoot.parentNode) {
      modalRoot.parentNode.removeChild(modalRoot)
    }
    
    // 查找遮罩层
    const masks = document.querySelectorAll('.ant-modal-mask')
    masks.forEach(mask => {
      if (mask.parentNode) {
        mask.parentNode.removeChild(mask)
      }
    })
  }

  useEffect(() => {
    // 组件卸载时清理
    return () => {
      cleanupModal()
    }
  }, [])

  // 监听模态框关闭
  useEffect(() => {
    if (!open) {
      cleanupModal()
    }
  }, [open])

  const handleOk = async (e: React.MouseEvent<HTMLElement>) => {
    if (form) {
      try {
        const values = await form.validateFields()
        await onFinish?.(values)
        form.resetFields()
      } catch (error) {
        console.error('Validate Failed:', error)
        return
      }
    }
    onOk?.(e)
  }

  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    form?.resetFields()
    onCancel?.(e)
    cleanupModal()
  }

  return (
    <div ref={modalRef}>
      <Modal
        {...props}
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        afterClose={() => {
          form?.resetFields()
          afterClose?.()
          cleanupModal()
        }}
        destroyOnClose
        maskClosable={false}
        keyboard={false}
      >
        {children}
      </Modal>
    </div>
  )
}

export default ProModal 